#include <platform/gles32_loader.h>

#include <EGL/egl.h>
#include <system_log.h>
#include <platform/dynamic_library.h>

namespace FFSdkUnity::Platform {

using LOADER_FUNC = decltype(&eglGetProcAddress);

static FF::Platform::DynamicLibrary g_egl{};
static LOADER_FUNC g_eglGetProcAddress = nullptr;

static void *FFAPI_PTR NativeGLES32Loader(char const *name, void * /* userData */)
{
    return reinterpret_cast<void *>(g_eglGetProcAddress(name));
}

bool GLES32::Init() noexcept
{
    if (!g_egl.Load("libEGL.so", FF::Platform::LibraryLoadPolicy::GLOBAL)) {
        return false;
    }

    g_eglGetProcAddress = reinterpret_cast<LOADER_FUNC>(g_egl.GetFunction("eglGetProcAddress"));

    if (g_eglGetProcAddress) {
        return true;
    }

    if (!Destroy()) {
        FFLOGW("Sdk::Unity::Platform::GLES32(android)::Init - Can't destroy system");
    }

    return false;
}

bool GLES32::Destroy() noexcept
{
    g_eglGetProcAddress = nullptr;
    return g_egl.Unload();
}

PFN_FrameFlow_ApiLoaderFunction GLES32::GetLoader() noexcept
{
    return &NativeGLES32Loader;
}

} // namespace FFSdkUnity::Platform
